import { zWarn } from "@/utils/console";
import { FormInst } from "naive-ui";
import { ref, Ref } from "vue";
import { ZFormMethods } from "../typings";
import { ZFormProps } from "../ZForm.vue";

export function useFormCore(props: ZFormProps, formRef: Ref<FormInst | null>) {
  const formValue = ref<any>({});

  function getDefaultValues() {
    return props.schemas.reduce<Record<string, any>>((a, c) => {
      a[c.path] = c.defaultValue ?? null; // TODO: set non-default-value to null
      return a;
    }, {});
  }

  /* methods */
  function validate() {
    if (formRef.value === null) {
      zWarn("Cannot call formRef before initialized");
      return Promise.reject();
    }
    return new Promise((res) => {
      formRef.value!.validate((errors) => {
        if (!errors) {
          res(formValue.value);
        }
      });
    });
  }

  function getFieldsValue() {
    return formValue.value;
  }

  /**
   * reset fields'value to its ${defaultValue}
   */
  function resetFields() {
    formValue.value = getDefaultValues();
  }

  function setFields(values: any) {
    formValue.value = values;
  }

  const formMethods: ZFormMethods = {
    validate,
    setFields,
    resetFields,
    getFieldsValue,
  };

  return { formValue, formMethods };
}
